package com.example.redismanual.dao.actionExamples.ZsetExamples;


import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Set;

/**
 * @Author xingxf03
 * @Date 14:41 2021/2/2
 * @Description
 *
 * 使用zset完成排行榜程序
 */

public class RankList {

    private ZSetOperations<String, String> client;

    private String uniKey;

    public RankList(ZSetOperations<String, String> client ,String uniKey){
        this.client = client;
        this.uniKey = uniKey;
    }

    public void setScore(String item,Double score){
        if (this.client.score(this.uniKey,item)==null){
            this.client.add(this.uniKey,item,score);
        }else {
            this.increScore(item,score);
        }
    }

    public Double getScore(String item){
        return this.client.score(this.uniKey,item);
    }

    public void removeItem(String item){
        this.client.remove(this.uniKey,item);
    }

    public Double increScore(String item,Double increment){
        return  this.client.incrementScore(this.uniKey,item,increment);
    }

    public Double decreScore(String item,Double decrement){
        return  this.client.incrementScore(this.uniKey,item,0 - decrement);
    }

    public Long rank(String item){
        Long result = this.client.rank(this.uniKey,item);
        if(result != null){
            return result ;
        }else {
         return  Long.parseLong("-1");
        }
    }

    public Set<String> topN(int n){
        return this.client.reverseRange(this.uniKey,0,n-1);
    }

    public Set<ZSetOperations.TypedTuple<String>> topNwithScore(int n){
        return this.client.reverseRangeWithScores(this.uniKey,0,n-1);
    }
}
